package com.bw.kf.playvideo

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import org.jash.playvideo.R
import org.jash.playvideo.databinding.ItemCommentBinding
import org.jash.playvideo.databinding.ItemReplyBinding

class CommentAdapter(
    private val comments: MutableList<CommentEntityItem>,
    private val onLikeClick: (CommentEntityItem) -> Unit,
    private val onReplyClick: (CommentEntityItem) -> Unit
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    companion object {
        private const val TYPE_COMMENT = 0
        private const val TYPE_REPLY = 1
        private const val TYPE_REPLY_LEVEL2 = 2
        private const val TYPE_REPLY_LEVEL3 = 3
        private const val MAX_LEVEL = 3 // 支持的最大评论层级（0-3，共4级）
    }

    private val expandedComments = mutableSetOf<Int>()

    class CommentViewHolder(val binding: ItemCommentBinding) : RecyclerView.ViewHolder(binding.root)
    class ReplyViewHolder(val binding: ItemReplyBinding) : RecyclerView.ViewHolder(binding.root)
    class ReplyLevel2ViewHolder(val binding: org.jash.playvideo.databinding.ItemReplyLevel2Binding) : RecyclerView.ViewHolder(binding.root)
    class ReplyLevel3ViewHolder(val binding: org.jash.playvideo.databinding.ItemReplyLevel3Binding) : RecyclerView.ViewHolder(binding.root)

    override fun getItemViewType(position: Int): Int {
        val comment = comments[position]
        return when {
            comment.parentId == null -> TYPE_COMMENT
            comment.level == 1 -> TYPE_REPLY
            comment.level == 2 -> TYPE_REPLY_LEVEL2
            else -> TYPE_REPLY_LEVEL3
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return when (viewType) {
            TYPE_COMMENT -> {
                val binding = ItemCommentBinding.inflate(
                    LayoutInflater.from(parent.context),
                    parent,
                    false
                )
                CommentViewHolder(binding)
            }
            TYPE_REPLY -> {
                val binding = ItemReplyBinding.inflate(
                    LayoutInflater.from(parent.context),
                    parent,
                    false
                )
                ReplyViewHolder(binding)
            }
            TYPE_REPLY_LEVEL2 -> {
                val binding = org.jash.playvideo.databinding.ItemReplyLevel2Binding.inflate(
                    LayoutInflater.from(parent.context),
                    parent,
                    false
                )
                ReplyLevel2ViewHolder(binding)
            }
            TYPE_REPLY_LEVEL3 -> {
                val binding = org.jash.playvideo.databinding.ItemReplyLevel3Binding.inflate(
                    LayoutInflater.from(parent.context),
                    parent,
                    false
                )
                ReplyLevel3ViewHolder(binding)
            }
            else -> throw IllegalArgumentException("Unknown view type: $viewType")
        }
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        val comment = comments[position]
        
        when (holder) {
            is CommentViewHolder -> bindComment(holder, comment, position)
            is ReplyViewHolder -> bindReply(holder, comment)
            is ReplyLevel2ViewHolder -> bindReplyLevel2(holder, comment)
            is ReplyLevel3ViewHolder -> bindReplyLevel3(holder, comment)
        }
    }

    private fun bindComment(holder: CommentViewHolder, comment: CommentEntityItem, position: Int) {
        val binding = holder.binding

        // 设置用户名
        binding.tvUserName.text = comment.nickname

        // 设置评论内容
        binding.tvCommentContent.text = comment.content

        // 设置评论时间
        binding.tvCommentTime.text = comment.createtime

        // 设置点赞按钮点击事件
        binding.ivLike.setOnClickListener {
            onLikeClick(comment)
        }

        // 设置回复按钮点击事件
        binding.tvReply.setOnClickListener {
            onReplyClick(comment)
        }

        // 设置点赞状态
        binding.ivLike.setColorFilter(
            if (comment.isLiked) {
                binding.root.context.getColor(android.R.color.holo_orange_light)
            } else {
                binding.root.context.getColor(android.R.color.black)
            }
        )

        // 处理回复列表
        val replies = comment.getSortedReplies()
        if (replies.isNotEmpty()) {
            binding.tvShowReplies.visibility = View.VISIBLE
            binding.tvShowReplies.text = if (expandedComments.contains(comment.id)) {
                "收起回复 (${replies.size})"
            } else {
                "查看回复 (${replies.size})"
            }
            
            binding.tvShowReplies.setOnClickListener {
                toggleReplies(comment.id, position)
            }
        } else {
            binding.tvShowReplies.visibility = View.GONE
        }
    }

    private fun bindReply(holder: ReplyViewHolder, reply: CommentEntityItem) {
        val binding = holder.binding

        // 设置用户名
        binding.tvUserName.text = reply.nickname

        // 设置回复内容，如果是回复某人则显示@用户名
        val content = if (reply.replyToUserName != null) {
            "@${reply.replyToUserName} ${reply.content}"
        } else {
            reply.content
        }
        binding.tvReplyContent.text = content

        // 设置回复时间
        binding.tvReplyTime.text = reply.createtime

        // 设置点赞按钮点击事件
        binding.ivLike.setOnClickListener {
            onLikeClick(reply)
        }

        // 设置回复按钮点击事件
        binding.tvReply.setOnClickListener {
            onReplyClick(reply)
        }

        // 设置点赞状态
        binding.ivLike.setColorFilter(
            if (reply.isLiked) {
                binding.root.context.getColor(android.R.color.holo_orange_light)
            } else {
                binding.root.context.getColor(android.R.color.black)
            }
        )
    }
    
    private fun bindReplyLevel2(holder: ReplyLevel2ViewHolder, reply: CommentEntityItem) {
        val binding = holder.binding

        // 设置用户名
        binding.tvUserName.text = reply.nickname

        // 设置回复内容，如果是回复某人则显示@用户名
        val content = if (reply.replyToUserName != null) {
            "@${reply.replyToUserName} ${reply.content}"
        } else {
            reply.content
        }
        binding.tvReplyContent.text = content

        // 设置回复时间
        binding.tvReplyTime.text = reply.createtime

        // 设置点赞按钮点击事件
        binding.ivLike.setOnClickListener {
            onLikeClick(reply)
        }

        // 设置回复按钮点击事件
        binding.tvReply.setOnClickListener {
            onReplyClick(reply)
        }

        // 设置点赞状态
        binding.ivLike.setColorFilter(
            if (reply.isLiked) {
                binding.root.context.getColor(android.R.color.holo_orange_light)
            } else {
                binding.root.context.getColor(android.R.color.black)
            }
        )
    }
    
    private fun bindReplyLevel3(holder: ReplyLevel3ViewHolder, reply: CommentEntityItem) {
        val binding = holder.binding

        // 设置用户名
        binding.tvUserName.text = reply.nickname

        // 设置回复内容，如果是回复某人则显示@用户名
        val content = if (reply.replyToUserName != null) {
            "@${reply.replyToUserName} ${reply.content}"
        } else {
            reply.content
        }
        binding.tvReplyContent.text = content

        // 设置回复时间
        binding.tvReplyTime.text = reply.createtime

        // 设置点赞按钮点击事件
        binding.ivLike.setOnClickListener {
            onLikeClick(reply)
        }

        // 设置回复按钮点击事件
        binding.tvReply.setOnClickListener {
            onReplyClick(reply)
        }

        // 设置点赞状态
        binding.ivLike.setColorFilter(
            if (reply.isLiked) {
                binding.root.context.getColor(android.R.color.holo_orange_light)
            } else {
                binding.root.context.getColor(android.R.color.black)
            }
        )
    }

    private fun toggleReplies(commentId: Int, position: Int) {
        val comment = comments[position]
        val replies = comment.getSortedReplies()
        
        if (expandedComments.contains(commentId)) {
            // 收起回复
            expandedComments.remove(commentId)
            val startIndex = position + 1
            
            // 计算要移除的项目数量（包括所有子回复）
            var itemsToRemove = 0
            var i = startIndex
            while (i < comments.size && (comments[i].parentId == commentId || comments[i].rootCommentId == commentId)) {
                itemsToRemove++
                i++
            }
            
            // 从列表中移除回复及其子回复
            for (j in 0 until itemsToRemove) {
                comments.removeAt(startIndex)
            }
            notifyItemRangeRemoved(startIndex, itemsToRemove)
        } else {
            // 展开回复
            expandedComments.add(commentId)
            
            // 处理回复的层级
            val processedReplies = replies.map { reply ->
                // 创建新的回复对象，设置层级和根评论ID
                if (reply.level == 0 || reply.rootCommentId == null) {
                    reply.copy(
                        level = if (reply.level == 0) 1 else reply.level,
                        rootCommentId = reply.rootCommentId ?: commentId
                    )
                } else {
                    reply
                }
            }
            
            // 在主评论后插入回复
            comments.addAll(position + 1, processedReplies)
            notifyItemRangeInserted(position + 1, processedReplies.size)
        }
        
        // 更新主评论的显示
        notifyItemChanged(position)
    }

    override fun getItemCount(): Int = comments.size

    fun updateComments(newComments: List<CommentEntityItem>) {
        comments.clear()
        // 只添加主评论，回复会在展开时动态添加
        comments.addAll(newComments.filter { it.parentId == null })
        expandedComments.clear()
        notifyDataSetChanged()
    }

    fun addComment(comment: CommentEntityItem) {
        if (comment.parentId == null) {
            // 主评论添加到顶部
            comments.add(0, comment)
            notifyItemInserted(0)
        } else {
            // 回复评论需要找到父评论并更新
            val parentComment = comments.find { it.id == comment.parentId }
            parentComment?.addReply(comment)
            
            // 如果是回复主评论
            if (comment.rootCommentId == comment.parentId) {
                // 如果父评论已展开，则插入回复
                val parentIndex = comments.indexOfFirst { it.id == comment.parentId }
                if (parentIndex != -1 && expandedComments.contains(comment.parentId)) {
                    val insertIndex = parentIndex + 1
                    comments.add(insertIndex, comment)
                    notifyItemInserted(insertIndex)
                }
                
                // 更新父评论显示
                if (parentIndex != -1) {
                    notifyItemChanged(parentIndex)
                }
            } else {
                // 如果是回复其他回复（多级评论）
                val rootCommentId = comment.rootCommentId
                if (rootCommentId != null && expandedComments.contains(rootCommentId)) {
                    // 找到父回复的位置
                    val parentIndex = comments.indexOfFirst { it.id == comment.parentId }
                    
                    if (parentIndex != -1) {
                        // 在父回复后插入新回复
                        val insertIndex = parentIndex + 1
                        comments.add(insertIndex, comment)
                        notifyItemInserted(insertIndex)
                    } else {
                        // 如果父回复不在当前显示列表中，则添加到根评论下的最后一个回复之后
                        val rootCommentIndex = comments.indexOfFirst { it.id == rootCommentId }
                        if (rootCommentIndex != -1) {
                            // 找到根评论下最后一个回复的位置
                            var lastReplyIndex = rootCommentIndex
                            for (i in rootCommentIndex + 1 until comments.size) {
                                if (comments[i].rootCommentId == rootCommentId) {
                                    lastReplyIndex = i
                                } else {
                                    break
                                }
                            }
                            
                            // 在最后一个回复后插入新回复
                            val insertIndex = lastReplyIndex + 1
                            comments.add(insertIndex, comment)
                            notifyItemInserted(insertIndex)
                        }
                    }
                }
                
                // 更新根评论显示（更新回复数量）
                val rootCommentIndex = comments.indexOfFirst { it.id == rootCommentId }
                if (rootCommentIndex != -1) {
                    notifyItemChanged(rootCommentIndex)
                }
            }
        }
    }
}
